package com.group.transaction.controller;

import com.group.transaction.common.HttpsUtil;
import com.group.transaction.model.ResultJson;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

@RestController
@RequestMapping("/userwx")
public class UserWXController {

    /**
     * 根据 code 获取 sessionKey 和 open id
     * @date
     * @return
     **/
    public ResultJson getSessionKey(String code) {
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
//        Map<String,String> requestUrlParam = new HashMap<>();
//        requestUrlParam.put("appid", "wx311dd33421f132de");  //开发者设置中的appId
//        requestUrlParam.put("secret", "9d202b8588de7030f7c691c6e91d59ac"); //开发者设置中的appSecret
//        requestUrlParam.put("js_code", code); //小程序调用wx.login返回的code
//        requestUrlParam.put("grant_type", "authorization_code");    //默认参数

        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        try {
            byte[] post = HttpsUtil.post(requestUrl, "appid=wx09f64ba06d108d5a&secret=9d202b8588de7030f7c691c6e91d59ac&js_code="+code+"&grant_type=authorization_code", "utf-8");
            String result = new String(post);
            return ResultJson.builder().code(1).message("发送成功").build();
        } catch (KeyManagementException | NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
            return ResultJson.builder().code(1).message("发送成功").build();
        }
    }
}
